package com.kevin.controller.controller.system;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fhs.core.trans.anno.TransMethodResult;
import com.kevin.common.api.R;
import com.kevin.common.constants.Constants;
import com.kevin.common.enums.LoginOperationEnum;
import com.kevin.common.exception.BusinessException;
import com.kevin.service.config.StpUserHolder;
import com.kevin.service.dto.LoginDTO;
import com.kevin.service.entity.SysUser;
import com.kevin.service.enums.UserType;
import com.kevin.service.service.SysLogLoginService;
import com.kevin.service.service.SysMenuService;
import com.kevin.service.service.SysUserService;
import com.kevin.service.vo.LoginResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

/**
 * 模拟身份验证控制器
 *
 * @author wh
 * @date 2023/03/27
 */
@Slf4j
@Api(tags = "授权管理")
@RestController
@RequestMapping(value = "auth")
@RequiredArgsConstructor
public class AuthController {
    private final SysUserService userService;
    private final SysMenuService menuService;
    private final SysLogLoginService logLoginService;
    private final PasswordEncoder passwordEncoder;

    @PostMapping(value = "login")
    @ApiOperation(value = "登录")
    public R<?> login(@RequestBody LoginDTO loginDTO) {
        return R.ok(l(loginDTO, UserType.BACK).getToken());
    }

    private LoginResult l(LoginDTO loginDTO, UserType userType) {
        SysUser user = userService.getOne(Wrappers.lambdaQuery(SysUser.builder().username(loginDTO.getUsername()).build()));
        if (user == null) {
            throw new BusinessException("用户不存在!");
        }
        if (!passwordEncoder.matches(loginDTO.getPassword(), user.getPassword())) {
            throw new BusinessException("密码错误");
        }
        if (user.getStatus() == 0) {
            throw new BusinessException("账号已被禁用");
        }
        StpUtil.login(user.getId());
        user.setPermissionList(menuService.getUserAuthority(user.getId(), user.getSuperAdmin()));
        StpUserHolder.setUserToSession(user);
        // 保存登录日志
        logLoginService.save(loginDTO.getUsername(), Constants.SUCCESS, LoginOperationEnum.LOGIN_SUCCESS.getValue());
        return LoginResult.builder().token(StpUtil.getTokenValue()).user(user).build();
    }

    @GetMapping(value = "info")
    @ApiOperation(value = "获取用户信息")
    @TransMethodResult
    public R<?> userInfo() {
        return R.ok(StpUserHolder.getUserFromSession());
    }

    @PostMapping(value = "logout")
    @ApiOperation(value = "登出")
    public R<?> logout() {
        StpUtil.logout();
        return R.ok();
    }

}
